/**
 * require SheetJS http://sheetjs.com
 * @author sunyu
 * 2016-03-07
 * usage
 * var ep = new ExcelUtil();
 * ep.read({
 *	"targetId":"xlf",
 *	"label":"Open an Excel file"
 *  },process_wb);
 *
 */
// event handler polyfill
function addEventListener(el, eventName, handler) {
	if (el.addEventListener) {
		el.addEventListener(eventName, handler);
	} else if (el.attachEvent) {
		el.attachEvent('on' + eventName, function(){
			handler.call(el);
		});
	}
}
//excel util
function ExcelUtil(params){
	this.error = '';
	params = params||{};
	// to show the errors if any, otherwise you can handle the errors using YourObject.errors
	this.showErrors = (params.showErrors === undefined ? true : params.showErrors);
	this.data = '';
}
ExcelUtil.prototype = {
	/**
	 * auto read file
	 */
	readAuto:function(params, onReady){
		var _this=this;
		if (typeof params === "function") {
			onReady=params;
			params={};
		}
		onReady = onReady || function() {};
		params.targetId = params.targetId || "upfile";
		params.label = params.label || "Load a file";
		if (document.getElementById(params.targetId) === null) {
			this.error = "[openLocal] You must have a targetId in your file.";
			this._showErrors();
			return this;
		}
		if (typeof FileReader === "function") {
			// So we use a regular input file
			//document.getElementById("me").outerHTML = '<input id="'+params.targetId+'" type="file" value="'+params.label+'" />';
			// add an event when loading the file
			addEventListener(document.getElementById(params.targetId), "change", function(e) {
				var files = e.target.files;
				var f = files[0];
				{
					var reader = new FileReader();
					reader.onload = function(e) {
						var data = e.target.result;
						var arr = _this.fixdata(data);
						var wb = XLSX.read(btoa(arr), {type: 'base64'});
						//process_wb(wb);
						onReady(wb);
					};
					reader.readAsArrayBuffer(f);
				}
			});
		}
	},
	/**
	 *
	 * @param params
	 * @param onReady
	 * 			function
	 * @returns {ExcelUtil}
     */
	read:function(params, onReady){
		var _this=this;
		if (typeof params === "function") {
			onReady=params;
			params={};
		}
		onReady = onReady || function() {};
		params.targetId = params.targetId || "upfile";
		params.label = params.label || "Load a file";
		if (document.getElementById(params.targetId) === null) {
			this.error = "[read] You must have a targetId in your file.";
			this._showErrors();
			return this;
		}
		if (typeof FileReader === "function") {
			//get files
			var files = document.getElementById(params.targetId).files;
			var f = files[0];
			if(f===undefined||f===null){
				this.error = "[read] You must have choose a file.";
				this._showErrors();
				return this;
			}
			var reader = new FileReader();
			reader.onload = function(e) {
				var data = e.target.result;
				var arr = _this.fixdata(data);
				var wb = XLSX.read(btoa(arr), {type: 'base64'});
				//process_wb(wb);
				onReady(wb);
			};
			reader.readAsArrayBuffer(f);
		}
	},
	to_json:function(workbook,readStart){
		var result = {};
		workbook.SheetNames.forEach(function(sheetName) {
			var roa = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName],{
				'readStart':readStart
			});
			if(roa.length > 0){
				result[sheetName] = roa;
			}
		});
		this.data = result;
		return result;
	},
	to_csv:function(workbook){
		var result = [];
		workbook.SheetNames.forEach(function(sheetName) {
			var csv = XLSX.utils.sheet_to_csv(workbook.Sheets[sheetName]);
			if(csv.length > 0){
				result.push("SHEET: " + sheetName);
				result.push("");
				result.push(csv);
			}
		});
		return result.join("\n");
	},
	to_formulae:function(workbook) {
		var result = [];
		workbook.SheetNames.forEach(function(sheetName) {
			var formulae = XLSX.utils.get_formulae(workbook.Sheets[sheetName]);
			if(formulae.length > 0){
				result.push("SHEET: " + sheetName);
				result.push("");
				result.push(formulae.join("\n"));
			}
		});
		return result.join("\n");
	},
	//default process to json
	process_wb:function(wb){
		var output = JSON.stringify(this.to_json(wb), 2, 2);
		//switch(get_radio_value("format")) {
		//	case "json":
		//		output = JSON.stringify(this.to_json(wb), 2, 2);
		//		break;
		//	case "form":
		//		output = this.to_formulae(wb);
		//		break;
		//	default:
		//	output = JSON.stringify(this.to_json(wb), 2, 2);
		//}
		//output= JSON.parse(output)
		//console.log("out:"+output[0][0]);
		if(out.innerText === undefined) out.textContent = output;
		else out.innerText = output;
		if(typeof console !== 'undefined') console.log("output", new Date());
	},
	fixdata:function(data){
		var o = "", l = 0, w = 10240;
		for(; l<data.byteLength/w; ++l) o+=String.fromCharCode.apply(null,new Uint8Array(data.slice(l*w,l*w+w)));
		o+=String.fromCharCode.apply(null, new Uint8Array(data.slice(l*w)));
		return o;
	},
	_showErrors:function() {
		if (this.showErrors) {
			if (this.error !== "") {
				throw "[ExcelUtil] "+this.error;
			}else{
				console.log("[ExcelUtil] No Error");
			}
		}
	}
};